using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace EnergyManagement.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class EnergyController : ControllerBase
    {
        private readonly ISqlSugarClient _db;
        
        public EnergyController(ISqlSugarClient db)
        {
            _db = db;
        }
        
        [HttpGet("monitor")]
        public async Task<IActionResult> GetMonitorData()
        {
            var now = DateTime.Now;
            var today = now.Date;
            
            // 获取今日能源数据
            var data = await _db.Queryable<EnergyData>()
                .Where(x => x.CollectionTime >= today && !x.IsDeleted)
                .ToListAsync();
                
            // 计算汇总数据
            var summary = data.GroupBy(x => x.EnergyType)
                .Select(g => new
                {
                    Type = g.Key,
                    Value = g.Sum(x => x.Value),
                    Unit = g.First().Unit
                })
                .ToList();
                
            return Ok(new { summary, details = data });
        }
        
        [HttpGet("analysis")]
        public async Task<IActionResult> GetAnalysisData([FromQuery] DateTime startTime, [FromQuery] DateTime endTime)
        {
            var data = await _db.Queryable<EnergyData>()
                .Where(x => x.CollectionTime >= startTime && x.CollectionTime <= endTime && !x.IsDeleted)
                .ToListAsync();
                
            // 计算同比环比数据
            // ...
            
            return Ok(data);
        }
        
        [HttpGet("warnings")]
        public async Task<IActionResult> GetWarnings()
        {
            var warnings = await _db.Queryable<EnergyWarning>()
                .Where(x => !x.IsDeleted)
                .OrderByDescending(x => x.WarningTime)
                .ToListAsync();
                
            return Ok(warnings);
        }
    }
}
